package cn.virens.web.components.weixin.config;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

public class WxMpRedisCacheConfigStorage extends WxMpAbstractCacheConfigStorage {
	private StringRedisTemplate redisTemplate;

	public WxMpRedisCacheConfigStorage(RedisConnectionFactory factory) {
		this.redisTemplate = new StringRedisTemplate();
		this.redisTemplate.setConnectionFactory(factory);
		this.redisTemplate.afterPropertiesSet();
	}

	@Override
	protected boolean has(String key) {
		return StringUtils.isEmpty(get(key));
	}

	@Override
	protected String get(String key) {
		if (redisTemplate != null) {
			return redisTemplate.opsForValue().get(key);
		} else {
			throw new NullPointerException("RedisTemplate is null");
		}
	}

	@Override
	protected void put(String key, String value, long timeout) {
		if (redisTemplate != null) {
			redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
		} else {
			throw new NullPointerException("RedisTemplate is null");
		}
	}
}
